import { FormDataTypeEnum, InputTypeEnum, Model } from 'easy-descriptor'
import { BaseModel } from '@/hooks/useModel'
import { rules } from '@/utils/validateRules'
import { RuleHandler } from '@/hooks/useModel/types'
import { FormItemRule, InputProps } from 'naive-ui'

import 'reflect-metadata'

@Model('SysUser')
export class SysUser extends BaseModel {
  @EField()
  $selection?: boolean

  @EField()
  $index?: number

  @EField('用户名', { sorter: true })
  @EField.Disabled(['edit'])
  username?: String

  @EField('用户编号', { sorter: true, formCompProps: { showButton: true } })
  @EField.Disabled(['form'])
  @EField.Hidden(['add'])
  userNo?: number

  @EField('密码')
  @EField.Hidden(['list', 'query'])
  password?: string

  @EField('手机号')
  phone?: string

  @EField('姓名')
  realName?: string

  @EField('性别')
  @EField.Dict()
  sex?: number

  @EField('生日')
  // @EField.DataType(FormDataTypeEnum.DATE)
  birthday?: Date

  @EField('邮箱')
  email?: string

  @EField('头像')
  avatar?: string

  @EField('角色', { render: ({ roles }) => roles?.map?.(({ roleName }) => roleName)?.join(','), formSpan: 2 })
  // @EField.DataType(FormDataTypeEnum.ARRAY)
  @EField.Dict('#sys_role')
  roles?: string[]

  @EField('部门', {
    render: ({ depts }) => depts?.map?.(({ deptName }) => deptName)?.join(','),
    formSpan: 2,
    inputProps: { topPid: '0', async: false }
  })
  @EField.DataType(FormDataTypeEnum.ARRAY, InputTypeEnum.TREE_SELECT)
  @EField.Dict('#sys_dept')
  depts?: string[]

  @EField('状态')
  @EField.Dict('SysUserStatus')
  // @EField.DataType(FormDataTypeEnum.NUMBER, InputTypeEnum.SWITCH)
  status?: number
}

const confirmPassword: RuleHandler<ChangeUserPassword> = ({ formData }) => {
  return [
    {
      required: true,
      message: '请再次输入密码',
      trigger: ['input', 'blur']
    },
    {
      trigger: ['input'],
      message: '两次密码不一致',
      validator: (_: FormItemRule, value: string) =>
        !!formData.value?.newPassword && formData.value.newPassword.startsWith(value) && formData.value.newPassword.length >= value.length
    },
    {
      validator: (_: FormItemRule, value: string): boolean => value === formData.value?.newPassword,
      message: '两次密码输入不一致',
      trigger: ['blur', 'password-input']
    }
  ]
}

const pwdCompProps: InputProps = {
  type: 'password',
  showPasswordOn: 'mousedown'
}

@Model({
  api: '/sys/user/changePasswordByOldPassword'
})
export class ChangeUserPassword extends BaseModel {
  @EField('原密码', { formItemProps: { rule: rules('required') }, formCompProps: pwdCompProps })
  oldPassword?: string

  @EField('新密码', { formItemProps: { rule: rules('required') }, formCompProps: pwdCompProps })
  newPassword?: string

  @EField('确认密码', { formItemProps: { ruleHandler: confirmPassword }, formCompProps: pwdCompProps })
  confirmPassword?: string
}

const field = (target: any, propertyKey: string) => {
  const metadata = Reflect.getMetadata('design:type', target, propertyKey)
  console.log(metadata)
}
